<template>
  <div class="login-container">
    <el-card class="box-card">
      <template #header>
        <span>登录</span>
      </template>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="100px" class="demo-loginForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="loginForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">登录</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { ElForm, ElFormItem, ElInput, ElButton, ElCard, ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { login } from '@/api/user';
import { useAllDataStore } from '@/stores';
import { useRouter } from 'vue-router';
import { menuAPI } from '@/api/menu';
import { permissionAPI } from '@/api/permission';

const router = useRouter();
const loginForm = reactive({
  username: '',
  password: ''
});

const rules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
};

const store = useAllDataStore();
//重置存储
store.resetStore();

const loginFormRef = ref<FormInstance | null>(null);

// 封装登录请求处理逻辑
interface LoginResponse {
  status_code: number;
  status: string;
  message?: string;
  data?: {
    api_key: string;
    username: string;
    token_key: string;
    role: string;
    email: string;
  };
}

const fetchLoginData = async () => {
  try {
    const responseData: LoginResponse = await login(loginForm); // 假设 login 返回的是 LoginResponse

    if (responseData.status_code === 200 && responseData.status === 'success') {
      store.setUsername(responseData.data?.username || '');
      store.setTokenKey(responseData.data?.token_key || '');
      await fetchLoginAfterData().then(() => {
        // 如果 fetchLoginAfterData 成功，则导航到主页面
        router.push('/main'); // 导航到 MainAsideCont.vue
      }).catch((error) => {
        // 如果 fetchLoginAfterData 失败，则显示错误消息
        ElMessage.error(`菜单或权限数据获取失败，请稍后再试: ${error.message || '未知错误'}`);
      });
    } else {
      ElMessage.error(`登录失败: ${responseData.message || '未知错误'}`);
    }
  } catch (error) {
    ElMessage.error(`登录请求失败，请稍后再试: ${error.message || '未知错误'}`);
  }
};


async function getMenu(): Promise<any> {
  const resultMenu =  await menuAPI(loginForm); // 假设 loginForm 包含必要的参数
  store.setMenuData(resultMenu);
 
}
 
async function getPermission(): Promise<any> {
  const resultPermission =  await permissionAPI(loginForm); // 假设 loginForm 包含必要的参数
  store.setPermissions(resultPermission);
 
}
// 获取菜单数据
const fetchLoginAfterData = async () => {
  try {
    await Promise.all([getMenu(), getPermission()]);

  }
  catch (error) {
    ElMessage.error(`菜单或权限数据获取失败，请稍后再试: ${error.message || '未知错误'}`);
  }
};

const submitForm = () => {
  if (!loginFormRef.value) return;
  loginFormRef.value.validate((valid) => {
    if (valid) {
      fetchLoginData();
    } else {
      console.log('验证失败!');
      ElMessage.error('验证失败!');
    }
  });
};

const resetForm = () => {
  if (!loginFormRef.value) return;
  loginFormRef.value.resetFields();
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f2f5;
}

.box-card {
  width: 480px;
}
</style>